#ifndef ASYNC_LOGGING_H
#define ASYNC_LOGGING_H

#include "Thread.h"
#include "LogBuffer.hpp"
#include "LogStream.hpp"
#include "LogFile.h"

#include <vector>
#include <memory>
#include <mutex>
#include <condition_variable>

namespace Logger
{
    class AsyncLogging
    {
    public:
        AsyncLogging(const std::string &baseName, off_t rollSize, int flushInterval = 3);
        ~AsyncLogging()
        {
            if (this->isRunning_)
            {
                this->stop();
            }
        }

        void start()
        {
            this->isRunning_ = true;
            this->thread_.start();
        }
        void stop()
        {
            this->isRunning_ = false;
            this->cond_.notify_one(); // 唤醒线程，检查状态标志，退出死循环
        }

        // 前端线程写缓冲内存-AsyncLogging-后端线程刷文件磁盘
        void append(const char *logLine, int len);

    private:
        void threadFunc();

        std::string baseName_; // 运行程序文件名，如testLogger.cpp，依据该名构造日志文件名
        off_t rollSize_;       // 文件滚动大小，单位B，到达该值后需要滚动
        int flushInterval_;    // 刷新间隔，单位s

        using LargeBuffer = LogBuffer<LogBuffer<0>::sLargeBufferSize>;
        using BufferVector = std::vector<std::unique_ptr<LargeBuffer>>;
        // BufferVector::value_type 是 std::vector<std::unique_ptr<Buffer>> 的元素类型，即 std::unique_ptr<Buffer>
        using BufferPtr = BufferVector::value_type;
        BufferPtr currBuffer_;
        BufferPtr nextBuffer_;
        BufferVector buffers_;

        Thread thread_;
        std::mutex mtx_;
        std::condition_variable cond_;

        std::atomic<bool> isRunning_;
    };
} // namespace Logger

#endif // ASYNC_LOGGING_H